import { ArrayMethods } from "./arr";
import Dep from "./compile/dep";
export function observer(data) {
  if (typeof data != "object" || data == null) {
    return data;
  }

  return new Observer(data);
}
class Observer {
  constructor(value) {
    this.dep = new Dep(); //我们要给所有对象类型添加一个dep
    Object.defineProperty(value, "__ob__", {
      value: this,
      enumerable: false,
      configurable: true,
    });
    //判断数据
    if (Array.isArray(value)) {
      value.__proto__ = ArrayMethods;
      this.observeArray(value);
    } else {
      this.walk(value);
    }
  }
  observeArray(value) {
    for (var i = 0; i < value.length; i++) {
      // console.log(value[i]);
      observer(value[i]);
    }
  }
  walk(data) {
    let keys = Object.keys(data);
    for (var i = 0; i < keys.length; i++) {
      let key = keys[i];

      let value = data[key];
      if (Array.isArray(value)) {
        observer(value);
        value.forEach((item) => {
          observer(item);
        });

        continue;
      }
      defineReactive(data, key, value);
    }
  }
}
//对对象中的每个属性进行劫持
function defineReactive(obj, key, value) {
  let childDep = observer(value); //深度代理
  let dep = new Dep(); // 给每一个属性添加一个dep

  Object.defineProperty(obj, key, {
    get() {
      if (Dep.target) {
        dep.depend();
        if (childDep.dep) {
          childDep.dep.depend(); //数组收集
        }
      }

      // console.log("得到了数据");
      return value;
    },
    set(newValu) {
      if (newValu === value) return;
      observer(newValu);
      value = newValu;

      dep.notify();
    },
  });
}
